#include "nameindex.h"
#include <common/constants.h>
#include <common/delegate.h>
#include <datasViewers/datasviewer.h>
#include <QUuid>

using namespace Constants;
using namespace Common;
using namespace Delegates;

NameIndex::NameIndex(){
  setupUi(this);
  m_db = QSqlDatabase::database(Constants::DATABASE_BMISURVEY);
  m_modelNames = new QSqlTableModel(this,m_db);
  m_modelDatas = new QSqlTableModel(this,m_db);
  m_modelDatas->setTable(WEIGHT_HEIGHT_TABLE);
  m_modelDatas->setFilter("");
  m_modelDatas->select();
  QDate defaultDate(1961,02,06);
  //weightEdit->setText("71");
  //heightEdit->setText("175");
  QDate dateOfDay = QDate::currentDate();
  dateEdit->setDisplayFormat("yyyy-MM-dd");
  dateEdit->setDate(dateOfDay);
  //nameisChosen("");
  showView();
  connect(addButton,SIGNAL(pressed()),this,SLOT(addValues()));
  connect(addNameButton,SIGNAL(pressed()),this,SLOT(addNameRow()));
  connect(tableView,SIGNAL(clicked(const QModelIndex&)),this,SLOT(fillTableWithTableviewChoice(const QModelIndex&)));
  connect(datasButton,SIGNAL(pressed()),this,SLOT(showWeightAndHeightDatas()));
  connect(allButton,SIGNAL(pressed()),this,SLOT(displayAllNames())); 
  connect(deleteNameButton,SIGNAL(pressed()),this,SLOT(deleteName()));  
}

NameIndex::~NameIndex(){}

bool NameIndex::createNameModel()
{
      bool b = true;
      showView();
      return b;
}

void NameIndex::showView()
{
  m_modelNames->setTable("nameindex");
  m_modelNames->setEditStrategy(QSqlTableModel::OnFieldChange);
  m_modelNames->select();
  m_modelNames->setHeaderData(NAME, Qt::Horizontal, tr("Name"));
  m_modelNames->setHeaderData(FIRSTNAME, Qt::Horizontal, tr("Firstname"));
  m_modelNames->setHeaderData(DATE_OF_BIRTH_DATA, Qt::Horizontal, tr("Date of birth"));
  tableView->setModel(m_modelNames);
  tableView->setItemDelegateForColumn(DATE_OF_BIRTH,new DateDelegate(this));
  tableView->setItemDelegateForColumn(GENDER,new ComboDelegate(this));
  tableView->hideColumn(ID_NAMEINDEX);
  tableView->hideColumn(UUID);  
  tableView->horizontalHeader()->resizeSections(QHeaderView::Interactive);
  tableView->horizontalHeader()->setStretchLastSection (true) ;
}


/*QList<QMultiMap<int,QString> > NameIndex::nameindexMapDatas() 
{
  QList<QMultiMap<int,QString> > list;
  QMultiMap<int,QString> dateH,weightH,heightH;
  QString name = nameEdit->text();
  QString firstname = firstnameEdit->text();
  QString dateOfBirth =  dateBirthEdit->date().toString("yyyy-MM-dd");
  QString patientUid = getPatientUuid(name,firstname,dateOfBirth);
  qDebug() << __FILE__ << QString::number(__LINE__) << " patientUuid =" << patientUid ;
  QString filter = QString("patient_uuid = '%1'").arg(patientUid);
  m_modelDatas->setFilter(filter);
  m_modelDatas->select();
  int rows = m_modelDatas->rowCount();
  int key = 0;
  for (int i = 0; i < rows; i += 1)
  {
        key++;
        QString date   = m_modelDatas->data(m_modelDatas->index(i,WH_INPUT_DATE)).toString();
        QString weight = m_modelDatas->data(m_modelDatas->index(i,WH_WEIGHT)).toString();
        QString height = m_modelDatas->data(m_modelDatas->index(i,WH_HEIGHT)).toString();
    	dateH.insertMulti(key,date);
     	weightH.insertMulti(key,weight);
    	heightH.insertMulti(key,height);
  	
  	if (!weight.isEmpty())
  	{
  		  m_hashOfNonEmptyWeightValues.insertMulti(date,weight);
  	    }
  	}
  list << dateH << weightH << heightH ;
  return list;
}*/

/*QStringList NameIndex::nameindexListDatas(){
  QStringList list;
  QString name = nameEdit->text();
  QString firstname = firstnameEdit->text();
  QString sex = "F";
  if(femaleRadioButton->isChecked()){
      sex = "F";
  }
  if(maleRadioButton->isChecked()){
      sex = "M";
  }
  QString weight = weightEdit->text();
  QString height = heightEdit->text();
  QString dateChosen = dateEdit->date().toString("yyyy-MM-dd");
  QString dateOfBirth =  dateBirthEdit->date().toString("yyyy-MM-dd");
  list << name            
       << firstname      
       << dateOfBirth    
       << sex            
       << weight         
       << height         
       << dateChosen;   
  return list;
}*/
//"id_NameIndex","name","firstname","date_of_birth"
void NameIndex::nameisChosen(const QString & filter)
{
    m_modelNames->clear();
    m_modelNames->setTable("nameindex");
    QString lFilter = QString("%1 LIKE '%2%'").arg("name",filter);
    
    m_modelNames->setFilter(lFilter);
    qDebug() << __FILE__ << QString::number(__LINE__) << " query =" << m_modelNames->filter() ;
    m_modelNames->select();
    showView();    
}

void NameIndex::fillTableWithTableviewChoice(const QModelIndex & index)
{
    int row = index.row();
    //m_modelNames->setFilter("");
    //m_modelNames->select();
    QAbstractItemModel *tableModel = tableView->model();
    if (row == 0 && tableModel->rowCount()<2)
    {
    	  return;
        }
    QString patientUuid = m_modelNames->data(m_modelNames->index(row,UUID),Qt::DisplayRole).toString();
    QString name = m_modelNames->data(m_modelNames->index(row,NAME),Qt::DisplayRole).toString();
    QString firstname = m_modelNames->data(m_modelNames->index(row,FIRSTNAME),Qt::DisplayRole).toString();
    QString dateOfBirthString = m_modelNames->data(m_modelNames->index(row,DATE_OF_BIRTH),Qt::DisplayRole).toString();
    QString gender = m_modelNames->data(m_modelNames->index(row,GENDER),Qt::DisplayRole).toString();
    getPatientUuid(name,firstname,dateOfBirthString);
}

QString NameIndex::getPatientUuid(QString & name, QString & firstname ,QString & dateOfBirth){
    QString uuid;
    QSqlTableModel *model = new QSqlTableModel(this,m_db);
    QString filter = QString("name = '%1' AND firstname = '%2' AND date_of_birth = '%3' ").arg(name,firstname,dateOfBirth);
    model->setFilter(filter);
    model->select();
    if (model->rowCount()>1)
    {
    	  QMessageBox::warning(0,trUtf8("Warning"),
    	                         trUtf8("Ce nom correspond à deux dossiers !"),
    	                         QMessageBox::Ok);
        }
    uuid = model->data(model->index(0,UUID),Qt::DisplayRole).toString();
    return uuid;
}

/*bool NameIndex::setNewPatientDatas(){//FIXME
    bool r = true;
    int row = m_modelNames->rowCount();
    int rowDatas = m_modelDatas->rowCount(); 
    if (!m_modelNames->insertRows(row,1))
    {
    	  qWarning() << __FILE__ << QString::number(__LINE__) << m_modelNames->query().lastError().text() ;
        }
    if (!m_modelDatas->insertRows(rowDatas,1))
    {
    	  qWarning() << __FILE__ << QString::number(__LINE__) << m_modelDatas->query().lastError().text() ;
        }
    int id_nameIndex = m_modelNames->data(m_modelNames->index(row-1,ID_NAMEINDEX),Qt::DisplayRole).toInt()+1;
    int id_dataIndex = m_modelDatas->data(m_modelNames->index(rowDatas-1,ID_WH),Qt::DisplayRole).toInt()+1;
    QString uuid = QUuid::createUuid ().toString();

    m_modelNames->setData(m_modelNames->index(row,ID_NAMEINDEX),id_nameIndex);
    m_modelNames->setData(m_modelNames->index(row,NAME),nameEdit->text());
    m_modelNames->setData(m_modelNames->index(row,FIRSTNAME),firstnameEdit->text());
    m_modelNames->setData(m_modelNames->index(row,DATE_OF_BIRTH),dateBirthEdit->date().toString("yyyy-MM-dd"));
    m_modelNames->setData(m_modelNames->index(row,UUID),uuid);
    m_modelNames->setData(m_modelNames->index(row,GENDER),gender,Qt::EditRole);
    m_modelDatas->setData(m_modelDatas->index(rowDatas,ID_WH),id_dataIndex);
    m_modelDatas->setData(m_modelDatas->index(rowDatas,WH_UUID),uuid);
    m_modelDatas->setData(m_modelDatas->index(rowDatas,WH_WEIGHT),weightEdit->text());
    m_modelDatas->setData(m_modelDatas->index(rowDatas,WH_HEIGHT),heightEdit->text());
    m_modelDatas->setData(m_modelDatas->index(rowDatas,WH_INPUT_DATE),dateEdit->date().toString("yyyy-MM-dd"));
    r = m_modelDatas->submitAll();
    r = m_modelNames->submitAll();
    return r;
}*/

void NameIndex::addValues(){
    QAbstractItemModel *model = tableView->model();
    if (model->rowCount()>1)
    {
          QMessageBox::warning(0,tr("Attention"),tr("Veuillez choisir un patient."),QMessageBox::Ok);
          return;
        }
    QString weightstring = weightEdit->text();
    QString heightstring = heightEdit->text();
    if (weightstring.isEmpty()||heightstring.isEmpty())
    {
          QMessageBox::warning(0,tr("Attention"),tr("Vous devez inscrire les valeurs poids taille !"),QMessageBox::Ok);
          return;
        }
    QString name = model->data(model->index(0,NAME),Qt::DisplayRole).toString();
    QString firstname = model->data(model->index(0,FIRSTNAME),Qt::DisplayRole).toString();
    QString dateOfBirth = model->data(model->index(0,DATE_OF_BIRTH),Qt::DisplayRole).toString();
    QString uuid = getPatientUuid(name,firstname,dateOfBirth);
    int rowDatas = m_modelDatas->rowCount();
    if (!m_modelDatas->insertRows(m_modelDatas->rowCount(),1))
    {
    	  qWarning() << __FILE__ << QString::number(__LINE__) << "unable to insert row" ;
        }
    int id_dataIndex = m_modelDatas->data(m_modelDatas->index(rowDatas-1,ID_WH),Qt::DisplayRole).toInt()+1;
    qDebug() << __FILE__ << QString::number(__LINE__) << " id_dataIndex =" << QString::number(id_dataIndex)
    << "rowDatas" << QString::number(rowDatas);
    m_modelDatas->setData(m_modelDatas->index(rowDatas,ID_WH),id_dataIndex);
    m_modelDatas->setData(m_modelDatas->index(rowDatas,WH_UUID),uuid);
    m_modelDatas->setData(m_modelDatas->index(rowDatas,WH_WEIGHT),weightstring);
    m_modelDatas->setData(m_modelDatas->index(rowDatas,WH_HEIGHT),heightstring);
    m_modelDatas->setData(m_modelDatas->index(rowDatas,WH_INPUT_DATE),dateEdit->date().toString("yyyy-MM-dd"));
    if (!m_modelDatas->submitAll())
    {
    	  qDebug() << __FILE__ << QString::number(__LINE__) << " error =" << m_modelDatas->lastError().text() ;
    	  QMessageBox::warning(0,trUtf8("Warning"),
    	                         trUtf8("Données non incluses"),
    	                         QMessageBox::Ok);
        }
    else{
        QMessageBox::information(0,tr("Information"),tr("Les données ont été intégrées."),QMessageBox::Ok);
        }
}

void NameIndex::addNameRow(){
    m_modelNames->setFilter("");
    //m_modelNames->setEditStrategy(QSqlTableModel::OnManualSubmit);    
    m_modelNames->select();
    int rows = m_modelNames->rowCount();
    if (!m_modelNames->insertRows(rows,1,QModelIndex()))
    {
          QMessageBox::warning(0,tr("Warning"),tr("Unable to insert row !"),QMessageBox::Ok);
        }
    for ( int col = 0; col < nameindexFieldsMaxParam; ++ col)
    {
          QVariant data = QVariant();
          if (col == UUID)
          {
                data = QVariant(); //FIXME
              }
          
          m_modelNames->setData(m_modelNames->index(rows,col),data,Qt::EditRole);
        }
    if (!m_modelNames->submitAll())
    {
          QString error = m_modelNames->lastError().text();
          QMessageBox::warning(0,tr("Warning"),tr("Unable to submit datas : \n")+error,QMessageBox::Ok);
        }
    tableView->setModel(m_modelNames);
}

/*bool NameIndex::nameExists(){
    bool b = true;
    qDebug() << __FILE__ << QString::number(__LINE__) << "in nameExists";
    QString name = nameEdit->text();
    QString firstname = firstnameEdit->text();
    QString dateOfBirth = dateBirthEdit->date().toString("yyyy-MM-dd");
    QString filter = QString("name = '%1' AND firstname = '%2' AND date_of_birth = '%3' ").arg(name,firstname,dateOfBirth);
    QSqlTableModel model(this,m_db);
    model.setTable("nameindex");
    model.setFilter(filter);
    model.select();
    qDebug() << __FILE__ << QString::number(__LINE__) << " query =" 
    << model.query().executedQuery() ;
    if (model.rowCount()<1)
    {
    	  int ret = QMessageBox::warning(0,trUtf8("Warning"),
    	                         trUtf8("Voulez vous enregistrer ce nom ? "),
    	                         QMessageBox::Ok | QMessageBox::Cancel);
          switch(ret){
              case QMessageBox::Ok :
                  setNewPatientDatas();
                  break;
              case QMessageBox::Cancel :
                  break;
              default :
                  break;    
              }
        }
    return b;
}*/

/*void NameIndex::fillEditsWithTableviewChoice(const QModelIndex & index)
{
    int row = index.row();
    qDebug() << __FILE__ << QString::number(__LINE__) << " ROW =" << QString::number(row) ;
    QSqlTableModel model(this,m_db);
    model.setTable("nameindex");
    model.setFilter("");
    model.select();
    QAbstractItemModel *tableModel = tableView->model();
    if (row == 0 && tableModel->rowCount()<2)
    {
    	  return;
        }
    QString patientUuid = model.data(model.index(row,UUID),Qt::DisplayRole).toString();
    QString name = model.data(model.index(row,NAME),Qt::DisplayRole).toString();
    QString firstname = model.data(model.index(row,FIRSTNAME),Qt::DisplayRole).toString();
    QString dateOfBirthString = model.data(model.index(row,DATE_OF_BIRTH),Qt::DisplayRole).toString();
    QDate dateOfBirth = QDate::fromString(dateOfBirthString,"yyyy-MM-dd");
    QString gender = model.data(model.index(row,GENDER),Qt::DisplayRole).toString();
    nameEdit->setText(name);
    firstnameEdit->setText(firstname);
    dateBirthEdit->setDate(dateOfBirth);
    if (gender.contains("F"))
    {
    	  femaleRadioButton->setChecked(true);
        }
    else if (gender.contains("M"))
    {
    	  maleRadioButton->setChecked(true);
        }
    else
    {
    	qWarning() << __FILE__ << QString::number(__LINE__) << "NO GENDER !" ;
        }
    QSqlTableModel modelDatas(this,m_db);
    QString filter = QString("%1 = '%2'").arg("patient_uuid",patientUuid);
    modelDatas.setTable(WEIGHT_HEIGHT_TABLE);
    modelDatas.setFilter(filter);
    modelDatas.select();
    QHash<QString,QString> dateWH;
    QString initDate("1900-01-01");
    dateWH.insert(initDate,"71:175");
    for (int i = 0; i < modelDatas.rowCount(); ++i)
    {
    	  QString w = modelDatas.data(modelDatas.index(i,WH_WEIGHT),Qt::DisplayRole).toString();
    	  QString h = modelDatas.data(modelDatas.index(i,WH_HEIGHT),Qt::DisplayRole).toString();
    	  QDate d = modelDatas.data(modelDatas.index(i,WH_INPUT_DATE),Qt::DisplayRole).toDate();
    	  if (d>QDate::fromString(dateWH.keys().last(),"yyyy-MM-dd"))
    	  {
    	  	  dateWH.clear();
    	  	  dateWH.insert(d.toString("yyyy-MM-dd"),w+":"+h);
    	      }
        }
        
     if (dateWH.count()>0)
     {
     	  
     	  QDate date = QDate::fromString(dateWH.keys()[0],"yyyy-MM-dd");     	  
     	  QString wh = dateWH.values()[0];
     	  QStringList lwh = wh.split(":");     	  
     	  if (lwh.size()>1)
     	  {
     	  	  weightEdit->setText(lwh[NI_WEIGHT]);
     	  	  qDebug() << __FILE__ << QString::number(__LINE__) << " weight =" << lwh[NI_WEIGHT] ;
     	  	  heightEdit->setText(lwh[NI_HEIGHT]);
     	  	  qDebug() << __FILE__ << QString::number(__LINE__) << " date =" << date.toString("yyyy-MM-dd") ;
     	  	  dateEdit->setDate(date);
     	      }
     	      
         }    
}*/

void NameIndex::showWeightAndHeightDatas()
{
    QString uuid;
    QAbstractItemModel *model = tableView->model();
    QModelIndex index = tableView->currentIndex();
    int row = -1;
    if (!index.isValid())
    {
    	  if (model->rowCount()==1)
    	  {
    	        row = 0;
    	      }
    	  else
    	  {
    	      QMessageBox::warning(0,trUtf8("Warning"),trUtf8("Please choose a line."),QMessageBox::Ok);
    	      return;
    	      }
        }
    else
    {
        row = index.row();
        }    
    uuid = model->data(model->index(row,UUID),Qt::DisplayRole).toString();    
    qWarning() << __FILE__ << QString::number(__LINE__) << " UUID =" << uuid ;
    DatasViewer *d = new DatasViewer(this,uuid);
    d->showDatas();
}

void NameIndex::displayAllNames()
{
    m_modelNames->setFilter("");
    m_modelNames->select();
}

/*QHash<QString,QString> NameIndex::getHashOfNonEmptyWeights()
{
    return m_hashOfNonEmptyWeightValues;
}*/

QStandardItemModel * NameIndex::getModelOfValues()
{
    //enum {SEX = 0, DATE_OF_BIRTH_DATA, TODAY , DATE , WEIGHT, HEIGHT,MaxEnum};
    QStandardItemModel *model = new QStandardItemModel(0,MaxDatasModelEnum);
    QAbstractItemModel *tableModel = tableView->model();
    if (tableModel->rowCount()>1)
    {
          QMessageBox::warning(0,tr("Attention"),tr("Veuillez choisir un patient."),QMessageBox::Ok);
        }
    QString name = tableModel->data(tableModel->index(0,NAME),Qt::DisplayRole).toString();
    QString firstname = tableModel->data(tableModel->index(0,FIRSTNAME),Qt::DisplayRole).toString();
    QString dateOfBirth = tableModel->data(tableModel->index(0,DATE_OF_BIRTH),Qt::DisplayRole).toString();
    QString patientUid = getPatientUuid(name,firstname,dateOfBirth);
    QString filter = QString("patient_uuid = '%1'").arg(patientUid);
    QString sex = tableModel->data(tableModel->index(0,GENDER),Qt::DisplayRole).toString();
    m_modelDatas->setFilter(filter);
    m_modelDatas->select();
    int rows = m_modelDatas->rowCount();
    for (int i = 0; i < rows; ++i)
    {
        QString today = QDate::currentDate().toString("yyyy-MM-dd");
        QString date   = m_modelDatas->data(m_modelDatas->index(i,WH_INPUT_DATE)).toString();
        QString weight = m_modelDatas->data(m_modelDatas->index(i,WH_WEIGHT)).toString();
        QString height = m_modelDatas->data(m_modelDatas->index(i,WH_HEIGHT)).toString();
        QStandardItem * sexItem = new QStandardItem(sex);
        QStandardItem * ageItem = new QStandardItem(dateOfBirth);
        QStandardItem * todayItem = new QStandardItem(today);
        QStandardItem * dateItem = new QStandardItem(date);
        QStandardItem * weightItem = new QStandardItem(weight);
        QStandardItem * heightItem = new QStandardItem(height);
        QList<QStandardItem *> listofitems;
        listofitems << sexItem << ageItem << todayItem << dateItem << weightItem << heightItem;
        model->appendRow(listofitems);
  	    }
    return model;
}

void NameIndex::deleteName()
{
    int row = tableView->currentIndex().row();
    if (tableView->model()->removeRows(row,1))
    {
          QMessageBox::information(0,tr("Information"),tr("La ligne a été effacée."),QMessageBox::Ok);
        }
}


